package space.hyf.config.security;

import space.hyf.model.vo.Result;
import space.hyf.utils.JacksonUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description: 未登录 拒绝访问
 * @ClassName: MyAuthenticationEntryPoint
 * @Author: HCode
 * @Date: 2023/3/14 15:12
 * @Version: 1.0
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    /**
     * 拦截未登录的
     * @param request 请求体
     * @param response 响应体
     * @param exception 认证异常
     * @throws IOException IO异常
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
            throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        Result result = Result.create(403, "请登录");
        out.write(JacksonUtils.writeValueAsString(result));
        out.flush();
        out.close();
    }
}
